package second.codeTop.package2;

import sun.reflect.generics.tree.Tree;
import util.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @ClassName LC103
 * @description:
 * @author: 荣燊
 * @create: 2022-04-02 14:35
 **/
public class LC103 {
    public static void main(String[] args) {

    }

    // 这不是之字形输出
    /**
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return res;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i=0; i<len; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            res.add(list);
        }
        return res;
    }
     **/

    // 之字型输出
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return res;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i=0; i<len; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            // 判断下list需不需要 逆序下
            if (res.size() % 2 != 0) {
                ArrayList<Integer> list1 = new ArrayList<>();
                for (int i=list.size()-1; i>=0; i--) {
                    list1.add(list.get(i));
                }
                res.add(list1);
            } else {
                res.add(list);
            }
        }
        return res;
    }
}
